package com.bds.btcdc.adapter.zb;

import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.adapter.bitstamp.utils.EncryDigestUtil;
import com.bds.btcdc.http.HttpUtil;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.adapter.zb.service.ZBTradeService;
import com.bds.btcdc.util.HttpUtilManager;
import com.bds.btcdc.util.MapSort;
import com.bds.btcdc.api.model.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by DongChenchen on 2018/5/8 0008
 */
public class ZBAPIClient {
    private static final Logger logger = LoggerFactory.getLogger(ZBTradeService.class);
    private String accessKey;
    private String secretKey;
    private static final String  URL_PREFIX="https://trade.zb.com/api/";
    private static ConcurrentMap<Long,ZBAPIClient> userAccess=new ConcurrentHashMap<>();
    private static ZBAPIClient client = null;
    private static ZBAPIClient client2 = null;
    public static ZBAPIClient getInstance(Long user_id,String accessKey,String secretKey) {
        if(!userAccess.containsKey(user_id)) {
            client=new ZBAPIClient(accessKey,secretKey);
            userAccess.put(user_id,client);
            return client;
        }
        return client;
    }
    public static ZBAPIClient getInstance() {
        if(client2==null) {
            client2=new ZBAPIClient();
            return client2;
        }
        return client2;
    }
    private ZBAPIClient() {
    }
    private ZBAPIClient(String accessKey,String secretKey) {
        this.accessKey=accessKey;
        this.secretKey=secretKey;
    }


    /**
     * 委托下单 request {"accesskey": your key, "amount": 0.01, "channel":
     * "ltcbtc_order", "event": "addChannel", "no": "14728151154382111746154",
     * "price": 100, "sign": 签名, "tradeType": 1 "acctType" : 1} response code :
     * 返回代码 message : 提示信息 id : 委托挂单号
     */
    public String makeOrder(Order order) {

        Result res=new Result();

        Map<String,String> params = new HashMap<>();
            params.put("accesskey",accessKey);
            params.put("method","order");
            params.put("amount",String.valueOf(order.getNum()));
            params.put("currency",order.getSymbol().toLowerCase());//需要下划线
            params.put("method","order");
            params.put("price",String.valueOf(order.getPrice()));
            params.put("tradeType","BUY".equals(order.getType().toUpperCase())?"1":"0");//交易类型1/0[buy/sell]
            String digest = EncryDigestUtil.digest(secretKey);
            String sign = EncryDigestUtil.hmacSign(MapSort.toStringMap(params), digest);
            params.put("sign",sign);
            params.put("reqTime",String.valueOf(Calendar.getInstance().getTimeInMillis()));
        try {
            String result  = HttpUtilManager.getInstance().requestHttpPost(URL_PREFIX, "order", params);
            logger.info("请求返回结果："+result);
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *  获取用户信息
     * @return
     *  //# Response
    {
        "result": {
            "coins": [
                {
                    "freez": "0.00000000",
                    "enName": "BTC",
                    "unitDecimal": 8,
                    "cnName": "BTC",
                    "unitTag": "฿",
                    "available": "0.00000000",
                    "key": "btc"
                },
                {
                    "freez": "0.00000000",
                    "enName": "LTC",
                    "unitDecimal": 8,
                    "cnName": "LTC",
                    "unitTag": "Ł",
                    "available": "0.00000000",
                    "key": "ltc"
                },
                ...
            ],
            "base": {
                "username": "134150***",
                "trade_password_enabled": true,
                "auth_google_enabled": false,
                "auth_mobile_enabled": true
            }
        }
    }
     */
    public String  getAccountInfo() {

        Map<String,String> params = new HashMap<>();
            params.put("accesskey",accessKey);
            params.put("method","getAccountInfo");
        String digest = EncryDigestUtil.digest(secretKey);
        String sign = EncryDigestUtil.hmacSign(MapSort.toStringMap(params), digest);
        params.put("sign",sign);
        params.put("reqTime",String.valueOf(Calendar.getInstance().getTimeInMillis()));
        try {
            String result  = HttpUtilManager.getInstance().requestHttpPost(URL_PREFIX, "getAccountInfo", params);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取最新交易价格，用于计算用户总金额
     * @param pair
     * @return
     */
    public BigDecimal getLastPrice(String pair){
        String url="http://api.zb.com/data/v1/ticker?market="+pair;
        try {
            String s = HttpUtil.getInstance().get(url, null, false);
            JSONObject res = JSONObject.parseObject(s);
            JSONObject ticker = res.getJSONObject("ticker");
            return  ticker.getBigDecimal("last");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 参数校验，都不能为空
     *
     * @return
     */
    private boolean volidate(Map<String, String> args) {
        for (Map.Entry<String, String> entry : args.entrySet()) {
            if (StringUtils.isEmpty(entry.getValue())) {
                return false;
            }
        }
        return true;
    }
}
